<?php
namespace LhpAmis\Plugin\ExcelControl;

use LhpAmis\util\AmisConfig;
use think\facade\Env;
use LhpAmis\Renderers\Custom;

class ExcelControl extends Custom
{
    protected array $options = [];

    protected array $extend_js_list = [

        '/static/LhpAmis/plugin/ExcelControl/jspreadsheet.js',
        '/static/LhpAmis/plugin/ExcelControl/jsuites.js',
    ];
    protected array $extend_css_list = [
        '/static/LhpAmis/plugin/ExcelControl/jspreadsheet.css',
        '/static/LhpAmis/plugin/ExcelControl/jsuites.css',
    ];

    public function __construct()
    {
        parent::__construct();
        Env::set('extend_css_list', $this->extend_css_list);
        Env::set('extend_js_list', $this->extend_js_list);
        $this->set('type', 'custom');
        $this->set('onMount', $this->onMount);
        $this->set('html', $this->html);
    }

    /**
     * 挂载js代码
     * @var string
     */
    protected string $onMount = <<<JS
        const jspreadsheet_doc = document.createElement('jspreadsheet');
        const columns = '|columns|';
        var options = {
            language: 'zh-cn',
            defaultColWidth: 100,
            allowInsertRow: true,
            minDimensions: [5, 10], 
        };
        let source = '|source|';
        source = JSON.parse(source);
        for (let key in source) {
            if (source.hasOwnProperty(key)) {
                options[key] = source[key];
            }
        }
          
  
        options.onchange = function () {
               // 获取列名称
               const headerstr = spreadsheet.getHeaders();
               const headers = headerstr.split(',');
               console.log(['headers',headers]);
                // 获取表格数据
                const data = spreadsheet.getData();

                // 合并列名称和数据
                const dataWithHeaders = data.map(row => {
                    const obj = {};
                    headers.forEach((header, index) => {
                        obj[header] = row[index];
                    });
                    return obj;
                });

     
            console.log(['getDataWithHeaders',dataWithHeaders]);
            onChange(spreadsheet.getData(false), 'excel');
        };
        let spreadsheet = jspreadsheet(jspreadsheet_doc, options);
        dom.appendChild(jspreadsheet_doc);
JS;
    protected string $html = "<input class='excel' type='text' hidden='hidden' name='excel' />";


    /**
     * 设置表格列
     * @param mixed $columns
     * @return static
     */
    public function columns($columns = '')
    {
        if (is_array($columns)) {
            $this->options['columns'] = $columns;
        }

        return $this;
    }

    /**
     * 所有表格可写
     * @param mixed $boolean
     * @return static
     */
    public function allowInsertRow($boolean = true)
    {
        $this->options['allowInsertRow'] = $boolean;
        return $this;
    }

    /**
     * 默认列宽
     * @param mixed $width
     * @return static
     */
    public function defaultColWidth($width = 100)
    {
        $this->options['defaultColWidth'] = $width;
        return $this;
    }

    /**
     * 最小行数和列数
     * @param mixed $columnsNumber
     * @param mixed $rowsNumber
     * @return static
     */
    public function minDimensions($columnsNumber = 10, $rowsNumber = 10)
    {
        $this->options['minDimensions'] = [$columnsNumber, $rowsNumber];
        return $this;
    }

    /**
     * 获取过滤后的结果
     * @return array
     */
    public function filteredResults(): array
    {
        $options = json_encode($this->options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $this->onMount = str_replace('|source|', $options, $this->onMount);

        $this->set('onMount', $this->onMount);
        return $this->amisSchema;
    }

    
    /**
     * 表单构建器字段初始化
     * @return void
     */
    public function formBuildField($item, $is_filter = false)
    {
        $this->valueFormat(AmisConfig::get('timeFormat'));
        $formatAttributes = $this->get_array_element_by_position($item,  5);
        if ($formatAttributes && is_string($formatAttributes)) {
            $this->set('valueFormat', $formatAttributes);
        }
        $this->extendsAttributes($item, 6);
        return $this;
    }

    /**
     * CURD构建器字段初始化
     * @return void
     */
    public function tableBuildField($item)
    {
        $this->extendsAttributes($item, 6);
        return $this;
    }
}
